'use client';

import { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import Image from 'next/image';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor';
import '@wangeditor/editor/dist/css/style.css';
import { fetchBookById, saveBookNote } from '../../actions/books';
import type { BookNote } from '../../types';
import '@wangeditor/editor/dist/css/style.css';
export default function BookNotePage() {
  const params = useParams();
  const router = useRouter();
  const [book, setBook] = useState<BookNote | null>(null);
  const [isEditing, setIsEditing] = useState(false);
  const [editor, setEditor] = useState<IDomEditor | null>(null);
  const [html, setHtml] = useState('');

  // Add this near the top of your component, with other configurations
  const toolbarConfig: Partial<IToolbarConfig> = {
    toolbarKeys: [
      'headerSelect',
      'blockquote',
      '|',
      'bold',
      'italic',
      'underline',
      'through',
      'color',
      'bgColor',
      '|',
      'bulletedList',
      'numberedList',
      'todo',
      '|',
      'justifyLeft',
      'justifyCenter',
      'justifyRight',
      '|',
      'link',
      'image',
      '|',
      'undo',
      'redo',
    ]
  };

  const editorConfig: Partial<IEditorConfig> = {
    placeholder: 'Start writing your note...',
    MENU_CONF: {}
  };

  // Load book data
  useEffect(() => {
    const loadBook = async () => {
      try {
        const data = await fetchBookById(params.id as string);
        setBook(data);
        setHtml(data.note || '');
      } catch (error) {
        console.error('Failed to fetch book:', error);
      }
    };

    loadBook();
  }, [params.id]);

  // Handle editor cleanup
  useEffect(() => {
    return () => {
      if (editor) {
        editor.destroy();
        setEditor(null);
      }
    };
  }, [editor]);

  // Handle edit mode changes
  const handleEditToggle = () => {
    if (isEditing) {
      // Cleanup editor before exiting edit mode
      if (editor) {
        editor.destroy();
        setEditor(null);
      }
    }
    setIsEditing(!isEditing);
  };

  const handleSave = async () => {
    if (!book || !editor) return;
    
    try {
      const content = editor.getHtml();
      await saveBookNote(book.id, content);
      setBook({ ...book, note: content });
      setHtml(content);
      handleEditToggle(); // Use the same function to exit edit mode
    } catch (error) {
      console.error('Failed to save note:', error);
    }
  };

  return (
    <div className="max-w-4xl mx-auto p-8">
      <button
        onClick={() => router.back()}
        className="mb-8 text-gray-600 hover:text-gray-800"
      >
        ← Back to Books
      </button>

      <div className="flex gap-8 mb-8">
        <Image
          src={book?.image || ''}
          alt={book?.title || ''}
          width={200}
          height={300}
          className="object-cover"
        />
        <div>
          <h1 className="text-3xl font-bold mb-2">{book?.title}</h1>
          <button
            onClick={handleEditToggle}  // Use the new handler
            className="px-4 py-2 bg-[#FF9851] text-white rounded-md hover:bg-[#FFB07F]"
          >
            {isEditing ? 'Cancel Edit' : 'Edit Note'}
          </button>
        </div>
      </div>

      <div className="bg-white rounded-lg p-6 shadow-lg">
        {isEditing ? (
          <div className="space-y-4">
            <div 
              style={{ 
                border: '1px solid #ccc', 
                borderRadius: '8px', 
                overflow: 'hidden',
                backgroundColor: 'white'
              }}
            >
              <Toolbar
                editor={editor}
                defaultConfig={toolbarConfig}
                mode="default"
                style={{ 
                  borderBottom: '1px solid #ccc',
                  backgroundColor: 'white',
                  padding: '8px'
                }}
              />
              <Editor
                defaultConfig={editorConfig}
                value={html}
                onCreated={setEditor}
                onChange={editor => setHtml(editor.getHtml())}
                mode="default"
                style={{ 
                  height: '500px',
                  padding: '20px',
                  backgroundColor: 'white',
                  color: 'black'
                }}
              />
            </div>
            <div className="flex justify-end space-x-4">
              <button
                onClick={() => setIsEditing(false)}
                className="px-4 py-2 text-gray-600 hover:text-gray-800"
              >
                Cancel
              </button>
              <button
                onClick={handleSave}
                className="px-4 py-2 bg-[#FF9851] text-white rounded-md hover:bg-[#FFB07F]"
              >
                Save Changes
              </button>
            </div>
          </div>
        ) : (
          <div 
            className="prose max-w-none"
            dangerouslySetInnerHTML={{ __html: book?.note || '' }}
          />
        )}
      </div>
    </div>
  );
}